using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Webkit;
using TMM.Controls;
using Android.Content.PM;
using Android.Provider;
using Android.Graphics;
using Java.IO;
using Android.Net;
using TMM.Common;

namespace TMM
{
    [Activity(Label = Constants.ApplicationName, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar", ScreenOrientation = ScreenOrientation.Portrait)]
    public class MainActivity : BaseActivity, IDialogInterfaceOnClickListener
    {
        public PictureData PictureData { get; private set; }
        public LocalDataBase LocalData { get; private set; }

        private WebView webView = null;
        private RelativeLayout menuLayout = null;
        private ImageButton menuButton = null;
        private TextView titleTextView = null;
        private NotificationsButtonView notificationsButtonView = null;
        private RelativeLayout mainLayout = null;
        private ImageView splashScreen = null;
        private ImageButton actionButton = null;
        private CameraData cameraData = null;
        private TMMWebViewClient TMMWebViewClient = null;

        public override void Initialize()
        {
            base.Initialize();

            SetContentView(Resource.Layout.Main);

            LocalData = new LocalData(this);

            menuLayout = FindViewById<RelativeLayout>(Resource.Id.menuLayout);
            menuButton = FindViewById<ImageButton>(Resource.Id.menuButton);
            titleTextView = FindViewById<TextView>(Resource.Id.titleTextView);
            notificationsButtonView = FindViewById<NotificationsButtonView>(Resource.Id.notificationsButton);
            mainLayout = FindViewById<RelativeLayout>(Resource.Id.mainLayout);
            splashScreen = FindViewById<ImageView>(Resource.Id.splashScreen);
            actionButton = FindViewById<ImageButton>(Resource.Id.actionButton);

            NotificationsManager.RegisterForGCMNotifications(this);

            webView = FindViewById<WebView>(Resource.Id.webView);
            webView.Settings.JavaScriptEnabled = true;
            webView.Settings.DomStorageEnabled = true;
            if (Debug.IsDebuggerConnected)
                webView.ClearCache(true);
            TMMWebViewClient = new TMM.TMMWebViewClient();
            webView.SetWebViewClient(TMMWebViewClient);
            webView.AddJavascriptInterface(new JS2CS(this), "Android");

            SetNumberOfNotifications(0);

            RegisterReceiver(new InternetBroadcastReceiver(this), new IntentFilter(ConnectivityManager.ConnectivityAction));

            LoadApplication();
        }

        public void SetNumberOfNotifications(int nr)
        {
            notificationsButtonView.SetNumber(nr);
        }

        public void SetTitle(string title)
        {
            titleTextView.Text = title;
        }

        public void ShowSplashScreen()
        {
            splashScreen.Visibility = ViewStates.Visible;
        }

        public void HideSplashScreen()
        {
            splashScreen.Visibility = ViewStates.Gone;
        }

        public void ShowMenu()
        {
            menuLayout.Visibility = ViewStates.Visible;
        }

        public void ReloadWebView()
        {
            webView.Reload();
        }

        public void HideMenu()
        {
            menuLayout.Visibility = ViewStates.Gone;
        }

        protected override void OnStart()
        {
            base.OnStart();

            menuButton.Click += ShowLeftMenu;
            notificationsButtonView.Click += ShowNotifications;
            actionButton.Click += BeginModuleAction;
        }

        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);

            if (intent.Action == "NOTIFICATION")
            {
                var ccdId = Intent.GetIntExtra("ccdId", 0);
                webView.LoadUrl("javascript:updateUnreadNotifications(" + ccdId.ToString() + ");");
            }
        }

        protected override void OnStop()
        {
            base.OnStop();

            menuButton.Click -= ShowLeftMenu;
            notificationsButtonView.Click -= ShowNotifications;
            actionButton.Click -= BeginModuleAction;
        }

        private void ShowLeftMenu(object sender, EventArgs e)
        {
            webView.LoadUrl("javascript:showLeftMenu();");
        }

        private void ShowNotifications(object sender, EventArgs e)
        {
            if (notificationsButtonView.NoNotifications > 0)
                webView.LoadUrl("javascript:showNotifications();");
        }

        private void BeginModuleAction(object sender, EventArgs e)
        {
            webView.LoadUrl("javascript:beginModuleAction();");
        }

        public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
        {
            if ((keyCode == Keycode.Back))
            {
                webView.LoadUrl("javascript:goBack();");
                return true;
            }

            return base.OnKeyDown(keyCode, e);
        }

        public void OnClick(IDialogInterface dialog, int which)
        {
            switch (CurrentAction)
            {
                case Actions.UpdatingApplication:
                    if (which == -1)
                    {
                        Intent marketIntent = new Intent(Intent.ActionView, UpdateUrl);
                        this.StartActivity(marketIntent);
                    }
                    else Finish();
                    break;
                case Actions.TakingPhoto:
                    DismissDialog((int)Dialogs.Photo);
                    if (which == 0)
                        new CameraHelper(this).CapturePicture((int)Actions.TakingPhoto);
                    else if (which == 1)
                        new CameraHelper(this).GetPictureFromLocalStorage((int)Actions.GettingPhotoFromDevice);
                    break;
            }
        }

        public void SetAction(string action)
        {
            actionButton.Visibility = ViewStates.Visible;

            if (action.Equals("More", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "navigation_more");
            else if (action.Equals("Search", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "action_search");
            else if (action.Equals("AddRequest", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "add_request");
            else if (action.Equals("Delete", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "content_delete");
            else if (action.Equals("Edit", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "content_edit");
            else if (action.Equals("History", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "content_history");
            else if (action.Equals("Save", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "content_save");
            else if (action.Equals("Refresh", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "navigation_refresh");
            else if (action.Equals("Camera", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "action_camera");
            else if (action.Equals("Email", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "action_email");
            else if (action.Equals("RatingHalf", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "action_favorites_half");
            else if (action.Equals("RatingEmpty", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "action_favorites_off");
            else if (action.Equals("RatingFull", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "action_favorites_on");
            else if (action.Equals("Login", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "action_login");
            else if (action.Equals("Settings", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "action_settings");
            else if (action.Equals("Upload", StringComparison.InvariantCultureIgnoreCase))
                UIHelper.SetIcon(this, actionButton, "content_image");
            else actionButton.Visibility = ViewStates.Gone;
        }

        public void GetPicture(string titleText, string cameraText, string galleryText, string cancelText)
        {
            cameraData = new CameraData()
            {
                CameraText = cameraText,
                CancelText = cancelText,
                GalleryText = galleryText,
                TitleText = titleText
            };

            ShowDialog((int)Dialogs.Photo);
        }

        protected override Dialog OnCreateDialog(int id)
        {
            Dialog dialog = null;

            if (id == (int)Dialogs.Photo)
            {
                CurrentAction = Actions.TakingPhoto;

                var items = new string[] { cameraData.CameraText, cameraData.GalleryText, cameraData.CancelText };
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.SetTitle(cameraData.TitleText);
                builder.SetItems(items, this);
                dialog = builder.Create();
            }

            return dialog;
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == (int)Actions.TakingPhoto)
            {
                if (data == null || string.IsNullOrWhiteSpace(data.DataString))
                    return;

                Bitmap photo = data.Extras.Get("data") as Bitmap;
                if (photo == null)
                    return;

                var pictureByteString = Converter.ConvertPictureTo64string(photo, null);
                if (string.IsNullOrWhiteSpace(pictureByteString))
                    return;

                PictureData = new PictureData()
                {
                    Data = pictureByteString
                };

                webView.LoadUrl("javascript:picDone();");
            }
            else if (requestCode == (int)Actions.GettingPhotoFromDevice)
            {
                if (data == null || string.IsNullOrWhiteSpace(data.DataString))
                    return;

                Android.Net.Uri selectedImage = data.Data;
                String[] filePathColumn = { MediaStore.Images.Media.InterfaceConsts.Data };

                var cursor = ContentResolver.Query(selectedImage, filePathColumn, null, null, null);
                cursor.MoveToFirst();

                int columnIndex = cursor.GetColumnIndex(filePathColumn[0]);
                String filePath = cursor.GetString(columnIndex);
                cursor.Close();

                int last = filePath.LastIndexOf(".");
                String ext = filePath.Substring(last + 1);

                last = filePath.LastIndexOf("/");
                var pictureName = filePath.Substring(last + 1);

                ext = ext.ToLower();
                if (ext != "jpg" && ext != "jpeg" && ext != "png")
                    return;

                Bitmap galleryPic = BitmapFactory.DecodeFile(filePath);
                var pictureByteString = Converter.ConvertPictureTo64string(galleryPic, filePath);
                if (string.IsNullOrWhiteSpace(pictureByteString))
                    return;

                PictureData = new PictureData()
                {
                    Data = pictureByteString
                };

                webView.LoadUrl("javascript:picDone();");
            }
        }

        public override void OnNoInternetAccess()
        {
            base.OnNoInternetAccess();

            webView.LoadUrl("file:///android_asset/www/noConnection.html");
            HideSplashScreen();
        }

        public void LoadApplication(string serverCode = null)
        {
            if (!HasAccessToInternet())
                return;

            var applicationUrl = Constants.ApplicationUrl;

            var serverToLoad = string.IsNullOrWhiteSpace(serverCode) ? new LocalData(this).GetLastServer() : serverCode;
            if (!string.IsNullOrWhiteSpace(serverToLoad))
            {
                var server = new ServersManager().GetServer(serverToLoad);
                applicationUrl = server != null ? server.ApplicationUrl.ToString() : Constants.ApplicationUrl;
            }

            webView.LoadUrl(applicationUrl);
        }

        public void Authenticate()
        {
            var authData = LocalData.GetAuthenticationData();
            if (authData == null)
                return;

            var command = string.Format("javascript:authenticate('{0}','{1}','{2}')", authData.ServerCode, authData.Username, authData.Password);

            LocalData.ResetAuthenticationData();

            webView.LoadUrl(command);
        }
    }
}